/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_port/data_center_bridging.h"

namespace dev {

bool NetworkPort_DataCenterBridging::update_dcbx_status_by_ncsi(uint8_t port_id) {
    ncsi_dcbx_status_t dcbx_status = {};
    bool ret = m_ncsi_over_mctp_huawei->get_dcbx_status(DEFAULT_PACKAGE_ID, port_id, &dcbx_status);
    if (!ret) {
        elog("Error: Failed to update DCBX status");
        return false;
    }
    Up2cos.set_value(
        std::vector<uint8_t>(dcbx_status.cos2_up, dcbx_status.cos2_up + MCTP_NCSI_DCBX_FIELD_LEN));
    Uppgid.set_value(
        std::vector<uint8_t>(dcbx_status.up_pgid, dcbx_status.up_pgid + MCTP_NCSI_DCBX_FIELD_LEN));
    Pgpct.set_value(
        std::vector<uint8_t>(dcbx_status.pgpct, dcbx_status.pgpct + MCTP_NCSI_DCBX_FIELD_LEN));
    PgStrict.set_value(
        std::vector<uint8_t>(dcbx_status.strict, dcbx_status.strict + MCTP_NCSI_DCBX_FIELD_LEN));
    Pfcmap.set_value(dcbx_status.pfcmap);
    return true;
}

void NetworkPort_DataCenterBridging::start_ncsi_update_task_huawei(
    ncsi_over_mctp_hw_ptr ncsi_over_mctp, mc::milliseconds interval, uint8_t port_id) {
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        update_dcbx_status_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_DataCenterBridging::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        delete m_ncsi_timer;
        m_ncsi_timer = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort_DataCenterBridging)